<template>
	<tm-app>
		<tm-sheet :margin="[24, 24]" v-if="product">
			<view class="flex flex-row flex-between">
				<tm-text v-if="!isEditingName" :font-size="42" class="text-weight-b" :label="product.name" @click="startEditName"></tm-text>
				<tm-input v-else v-model="editingName" :font-size="42" :shadow="2" :round="25" @blur="saveName" @confirm="saveName"></tm-input>
			</view>
			<tm-money fontSize="28" preFontSize="24" symbolText="总成本: ￥" :modelValue="totalCost" :digit="2"></tm-money>
		</tm-sheet>

		<tm-sheet :margin="[24, 24]">
			<tm-text :font-size="28" class="mb-10" label="配件名称"></tm-text>
			<tm-input v-model="newAccessory.name" placeholder="请输入配件名称" :shadow="2" :round="25"></tm-input>
			<tm-text :font-size="28" class="mb-10 mt-20" label="配件单价"></tm-text>
			<tm-input v-model.number="newAccessory.price" type="number" placeholder="请输入配件单价" :shadow="2" :round="25"></tm-input>
			<tm-text :font-size="28" class="mb-10 mt-20" label="配件数量"></tm-text>
			<tm-input v-model.number="newAccessory.quantity" type="number" placeholder="请输入配件数量" :shadow="2" :round="25"></tm-input>
			<view class="flex flex-row flex-between mt-20">
				<tm-text :font-size="28" label="配件金额:"></tm-text>
				<tm-money fontSize="28" preFontSize="24" :modelValue="accessoryTotal" :digit="2"></tm-money>
			</view>
			<tm-button @click="addAccessory" :shadow="2" :round="25" block class="mt-20">添加配件</tm-button>
		</tm-sheet>

		<tm-sheet :margin="[24, 24]">
			<tm-text :font-size="32" class="text-weight-b" label="配件列表"></tm-text>
			<view v-if="!product || product.accessories.length === 0" class="flex-center pa-24">
				<tm-text color="grey" label="暂无配件，请先添加"></tm-text>
			</view>
			<tm-card v-for="(accessory, index) in product.accessories" :key="index" :margin="[0, 24]">
				<view class="flex flex-row flex-between">
					<view class="flex-1" @click="editAccessory(index)">
						<tm-text :font-size="28" :label="accessory.name"></tm-text>
					</view>
					<view class="flex flex-row flex-center">
						<view class="flex flex-col text-align-right mr-16">
							<tm-text :font-size="28" :label="`¥${accessory.price} x ${accessory.quantity}`"></tm-text>
							<tm-money fontSize="28" preFontSize="24" :modelValue="accessory.price * accessory.quantity" :digit="2"></tm-money>
						</view>
						<tm-button @click.stop="deleteAccessory(index)" color="error" size="s">删除</tm-button>
					</view>
				</view>
			</tm-card>

			<tm-modal v-model:show="showEditModal" :title="'编辑配件'" :showFooter="false" :height="700">
				<template v-if="editingAccessory !== null">
					<tm-text :font-size="28" class="mb-10" label="配件名称"></tm-text>
					<tm-input v-model="editingAccessory.name" placeholder="请输入配件名称" :shadow="2" :round="25"></tm-input>
					<tm-text :font-size="28" class="mb-10 mt-20" label="配件单价"></tm-text>
					<tm-input v-model.number="editingAccessory.price" type="number" placeholder="请输入配件单价" :shadow="2" :round="25"></tm-input>
					<tm-text :font-size="28" class="mb-10 mt-20" label="配件数量"></tm-text>
					<tm-input
						v-model.number="editingAccessory.quantity"
						type="number"
						placeholder="请输入配件数量"
						:shadow="2"
						:round="25"
					></tm-input>
					<view class="flex flex-row flex-center mt-20">
						<tm-button @click="saveAccessory" :shadow="2" :round="25" block>保存</tm-button>
					</view>
				</template>
			</tm-modal>
			<tm-button v-if="product.accessories.length > 0" @click="copyToClipboard" :shadow="2" :round="25" block class="mt-20">
				复制到剪贴板
			</tm-button>
		</tm-sheet>
	</tm-app>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useProductStore } from '../../store/product'

const store = useProductStore()
const product = ref(null)
const newAccessory = ref({ name: '', price: 0, quantity: 1 })

// 产品名称编辑相关
const isEditingName = ref(false)
const editingName = ref('')

const startEditName = () => {
	editingName.value = product.value.name
	isEditingName.value = true
}

const saveName = () => {
	if (editingName.value.trim()) {
		store.updateProductName(product.value.id, editingName.value)
	}
	isEditingName.value = false
}

// 配件编辑相关
const showEditModal = ref(false)
const editingAccessory = ref(null)
const editingIndex = ref(-1)

const editAccessory = (index) => {
	editingIndex.value = index
	editingAccessory.value = { ...product.value.accessories[index] }
	showEditModal.value = true
}

const saveAccessory = () => {
	if (editingAccessory.value.name && editingAccessory.value.price > 0 && editingAccessory.value.quantity > 0) {
		store.updateAccessory(product.value.id, editingIndex.value, editingAccessory.value)
		showEditModal.value = false
	}
}

const deleteAccessory = (index) => {
	uni.showModal({
		title: '确认删除',
		content: '确定要删除这个配件吗？',
		success: function (res) {
			if (res.confirm) {
				store.deleteAccessory(product.value.id, index)
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
			}
		}
	})
}

const accessoryTotal = computed(() => {
	return (newAccessory.value.price || 0) * (newAccessory.value.quantity || 0)
})

const totalCost = computed(() => {
	if (!product.value) return 0
	return product.value.accessories.reduce((total, acc) => total + acc.price * acc.quantity, 0)
})

function addAccessory() {
	store.addAccessory(product.value.id, { ...newAccessory.value })
	newAccessory.value = { name: '', price: 0, quantity: 1 }
}

function copyToClipboard() {
	if (!product.value) return

	let clipboardText = `产品名称: ${product.value.name}\n`
	clipboardText += `总成本: ¥${totalCost.value.toFixed(2)}\n`
	clipboardText += '配件列表:\n'

	if (product.value.accessories.length > 0) {
		product.value.accessories.forEach((acc) => {
			const accessoryTotal = acc.price * acc.quantity
			clipboardText += `- ${acc.name}: ¥${acc.price} x ${acc.quantity} = ¥${accessoryTotal.toFixed(2)}\n`
		})
	} else {
		clipboardText += '无\n'
	}

	uni.setClipboardData({
		data: clipboardText,
		success: function () {
			uni.showToast({
				title: '已复制到剪贴板',
				icon: 'success'
			})
		}
	})
}

onLoad((options) => {
	product.value = store.getProduct(options.id)
})
</script>
